package com.multiplay.tetris;

import java.util.Timer;
import java.util.TimerTask;

import com.multiplay.GlobalDefs;
import com.multiplay.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class MainWindow extends Activity 
{
    protected Timer timer = null;
    protected PlayFieldView play_field = null;
    protected boolean btns_active = false;
	
    public MainWindow()
    {
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.v(GlobalDefs.LOG_APP_TAG, "MainWindow: onCreate entered");

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        setContentView(R.layout.tetris);

        play_field = (PlayFieldView)findViewById(R.id.play_field);
        
        start_timer(1000);
    }
    
    public void start_timer(int period)
    {
        timer = new Timer();
        timer.schedule(new TimerTask() 
        {
            @Override
            public void run() 
            {
                timer_method();
            }
        }, 0, period);
        btns_active = true;
    }
    
    public void stop_timer()
    {
    	btns_active = false;
        timer.cancel();
        timer.purge();
    }
    
    private void timer_method()
    {
        runOnUiThread(timer_tick);
    }

    private Runnable timer_tick = new Runnable() 
    {
        public void run() 
        {
            play_field.timer_tick();
        }
    };
    
    public void left_button(View view)
    {
    	if (play_field != null && btns_active)
    		play_field.step_left();
    }
    
    public void right_button(View view)
    {
    	if (play_field != null && btns_active)
    		play_field.step_right();
    }
    
    public void drop_button(View view)
    {
    	if (play_field != null && btns_active)
    		play_field.drop_block();
    }
    
    public void rotate_button(View view)
    {
    	if (play_field != null && btns_active)
    		play_field.rotate_block();
    }
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        
        stop_timer();
        Log.v(GlobalDefs.LOG_APP_TAG, "MainWindow: onDestroy entered");
    }
}
